<template>
  <div class="multi-garment-upload">
    <div class="upload-label">
      <span class="label-icon">👔</span>
      <span class="label-text">服装照片</span>
      <el-tag size="small" type="warning">可添加多件</el-tag>
    </div>
    
    <!-- 服装卡片网格 -->
    <div class="garments-grid">
      <!-- 现有服装卡片 -->
      <div 
        v-for="(garment, index) in modelValue" 
        :key="garment.id"
        class="garment-card"
      >
        <!-- 服装类型选择 -->
        <el-select 
          v-model="garment.type" 
          placeholder="选择类型"
          size="small"
          class="garment-type-select"
        >
          <el-option label="上衣" value="upper">
            <span>👕 上衣</span>
          </el-option>
          <el-option label="裤子" value="lower">
            <span>👖 裤子</span>
          </el-option>
          <el-option label="裙子" value="dress">
            <span>👗 裙子</span>
          </el-option>
          <el-option label="外套" value="coat">
            <span>🧥 外套</span>
          </el-option>
          <el-option label="鞋子" value="shoes">
            <span>👟 鞋子</span>
          </el-option>
          <el-option label="配饰" value="accessories">
            <span>🎒 配饰</span>
          </el-option>
        </el-select>
        
        <!-- 上传区域 -->
        <el-upload
          class="garment-upload"
          drag
          :http-request="(options) => handleUpload(options, index)"
          :before-upload="beforeUpload"
          :show-file-list="false"
          :disabled="!garment.type"
        >
          <div v-if="!garment.imageUrl && !garment.uploading" class="upload-placeholder-mini">
            <el-icon><UploadFilled /></el-icon>
            <div class="upload-text-mini">
              {{ garment.type ? '点击上传' : '先选类型' }}
            </div>
          </div>
          <div v-else-if="garment.uploading" class="uploading-state">
            <el-icon class="is-loading"><Loading /></el-icon>
            <div>上传中...</div>
          </div>
          <div v-else class="garment-preview">
            <img :src="garment.imageUrl" alt="服装" />
            <div class="garment-type-badge">
              {{ getGarmentTypeLabel(garment.type) }}
            </div>
            <div class="preview-overlay">
              <el-icon class="overlay-icon"><RefreshRight /></el-icon>
              <span>重新上传</span>
            </div>
          </div>
        </el-upload>
        
        <!-- 服装名称输入 -->
        <el-input
          v-if="garment.imageUrl"
          v-model="garment.name"
          placeholder="名称（可选）"
          size="small"
          class="garment-name-input"
        >
          <template #prepend>
            <el-icon><Edit /></el-icon>
          </template>
        </el-input>
        
        <!-- 删除按钮 -->
        <el-button
          type="danger"
          size="small"
          :icon="Delete"
          circle
          class="remove-garment-btn"
          @click="removeGarment(index)"
          title="删除此服装"
        />
      </div>
      
      <!-- 添加服装按钮 -->
      <div 
        v-if="modelValue.length < maxGarments"
        class="add-garment-card" 
        @click="addGarment"
      >
        <el-icon class="add-icon"><Plus /></el-icon>
        <div class="add-text">添加服装</div>
        <div class="add-hint">{{ modelValue.length }}/{{ maxGarments }}</div>
      </div>
    </div>
    
    <!-- 提示信息 -->
    <div v-if="modelValue.length > 0" class="garment-tips">
      <el-icon><InfoFilled /></el-icon>
      <span>已添加 {{ modelValue.filter(g => g.imageUrl).length }}/{{ modelValue.length }} 件服装，
        可同时搭配上衣、裤子、鞋子等进行试穿</span>
    </div>
  </div>
</template>

<script setup>
import { defineProps, defineEmits } from 'vue'
import { ElMessage } from 'element-plus'
import {
  UploadFilled,
  Delete,
  Plus,
  InfoFilled,
  Edit,
  RefreshRight,
  Loading
} from '@element-plus/icons-vue'
import api from '@/composables/useApi'

const props = defineProps({
  modelValue: {
    type: Array,
    default: () => []
  },
  userId: {
    type: Number,
    required: true
  },
  maxGarments: {
    type: Number,
    default: 5
  }
})

const emit = defineEmits(['update:modelValue'])

// 创建新服装对象
const createGarmentObject = () => ({
  id: Date.now() + Math.random(),
  imageUrl: '',
  type: '',
  name: '',
  remarks: '',
  saveToLibrary: false,
  uploading: false,
  garmentId: null
})

// 添加服装
const addGarment = () => {
  if (props.modelValue.length >= props.maxGarments) {
    ElMessage.warning(`最多添加 ${props.maxGarments} 件服装`)
    return
  }
  
  const newGarments = [...props.modelValue, createGarmentObject()]
  emit('update:modelValue', newGarments)
  ElMessage.success('已添加新服装卡片')
}

// 删除服装
const removeGarment = (index) => {
  const newGarments = props.modelValue.filter((_, i) => i !== index)
  emit('update:modelValue', newGarments)
  ElMessage.info('已删除服装')
}

// 文件上传前验证
const beforeUpload = (file) => {
  console.log('📤 上传文件信息:', {
    name: file.name,
    type: file.type,
    size: file.size
  })
  
  const validTypes = [
    'image/jpeg',
    'image/jpg', 
    'image/png',
    'image/heic',
    'image/heif',
    ''
  ]
  
  const isValidType = validTypes.includes(file.type) || 
                     file.name.match(/\.(jpg|jpeg|png|heic|heif)$/i)
  
  if (!isValidType) {
    ElMessage.error('只能上传 JPG/PNG/HEIC 格式的图片！')
    return false
  }
  
  if (file.size > 0) {
    const isLt10M = file.size / 1024 / 1024 < 10
    if (!isLt10M) {
      ElMessage.error('图片大小不能超过 10MB！')
      return false
    }
  } else {
    ElMessage.info('正在从 iCloud 下载照片，请稍候...')
  }
  
  return true
}

// 处理上传
const handleUpload = async (options, index) => {
  const { file, onProgress, onSuccess, onError } = options
  
  const garment = props.modelValue[index]
  if (!garment.type) {
    ElMessage.warning('请先选择服装类型')
    if (onError) onError(new Error('未选择类型'))
    return
  }
  
  try {
    // 更新上传状态
    const newGarments = [...props.modelValue]
    newGarments[index] = { ...garment, uploading: true }
    emit('update:modelValue', newGarments)
    
    ElMessage.info(`正在上传${getGarmentTypeLabel(garment.type)}...`)
    
    const formData = new FormData()
    formData.append('file', file)
    formData.append('userId', props.userId)
    formData.append('garmentType', garment.type)
    formData.append('saveToLibrary', garment.saveToLibrary)
    
    if (garment.name) {
      formData.append('garmentName', garment.name)
    }
    
    const response = await api.post('/tryon/upload/garment', formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
      onUploadProgress: (progressEvent) => {
        const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total)
        if (onProgress) onProgress({ percent })
      }
    })
    
    // 更新服装信息
    const updatedGarments = [...props.modelValue]
    updatedGarments[index] = {
      ...garment,
      imageUrl: response.data.url,
      garmentId: response.data.garmentId,
      uploading: false
    }
    emit('update:modelValue', updatedGarments)
    
    ElMessage.success(`${getGarmentTypeLabel(garment.type)}上传成功 ✨`)
    
    if (onSuccess) onSuccess(response.data)
  } catch (error) {
    console.error('上传失败:', error)
    
    // 重置上传状态
    const resetGarments = [...props.modelValue]
    resetGarments[index] = { ...garment, uploading: false }
    emit('update:modelValue', resetGarments)
    
    ElMessage.error('上传失败，请重试')
    if (onError) onError(error)
  }
}

// 获取服装类型标签
const getGarmentTypeLabel = (type) => {
  const labels = {
    upper: '上衣',
    lower: '裤子',
    dress: '裙子',
    coat: '外套',
    shoes: '鞋子',
    accessories: '配饰'
  }
  return labels[type] || type
}
</script>

<style scoped>
.multi-garment-upload {
  width: 100%;
}

.upload-label {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  margin-bottom: 1rem;
  font-weight: 600;
  color: #1e293b;
  font-size: 1rem;
}

.label-icon {
  font-size: 1.5rem;
}

/* 服装卡片网格 */
.garments-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
  gap: 1rem;
  margin-bottom: 1rem;
}

/* 服装卡片 */
.garment-card {
  position: relative;
  background: white;
  border: 2px dashed #d946ef;
  border-radius: 12px;
  padding: 0.75rem;
  transition: all 0.3s ease;
}

.garment-card:hover {
  border-color: #c026d3;
  box-shadow: 0 4px 12px rgba(217, 70, 239, 0.2);
  transform: translateY(-2px);
}

/* 服装类型选择 */
.garment-type-select {
  width: 100%;
  margin-bottom: 0.5rem;
}

/* 上传区域 */
.garment-upload {
  width: 100%;
  margin-bottom: 0.5rem;
}

.garment-upload :deep(.el-upload) {
  width: 100%;
}

.garment-upload :deep(.el-upload-dragger) {
  width: 100%;
  height: 140px;
  padding: 0;
  border-radius: 8px;
}

/* 上传占位符 */
.upload-placeholder-mini {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #d946ef;
}

.upload-placeholder-mini .el-icon {
  font-size: 2rem;
  margin-bottom: 0.5rem;
}

.upload-text-mini {
  font-size: 0.875rem;
  font-weight: 500;
}

/* 上传中状态 */
.uploading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #d946ef;
  font-size: 0.875rem;
}

.uploading-state .el-icon {
  font-size: 2rem;
  margin-bottom: 0.5rem;
}

/* 服装预览 */
.garment-preview {
  position: relative;
  width: 100%;
  height: 140px;
  border-radius: 8px;
  overflow: hidden;
  background: #f5f5f5;
}

.garment-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.garment-type-badge {
  position: absolute;
  top: 0.5rem;
  left: 0.5rem;
  padding: 0.25rem 0.6rem;
  background: rgba(217, 70, 239, 0.95);
  color: white;
  border-radius: 8px;
  font-size: 0.75rem;
  font-weight: 600;
  backdrop-filter: blur(4px);
}

.preview-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(217, 70, 239, 0.9);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  opacity: 0;
  transition: opacity 0.3s ease;
  color: white;
  font-weight: 600;
  font-size: 0.875rem;
}

.garment-preview:hover .preview-overlay {
  opacity: 1;
}

.overlay-icon {
  font-size: 1.5rem;
}

/* 服装名称输入 */
.garment-name-input {
  font-size: 0.875rem;
}

/* 删除按钮 */
.remove-garment-btn {
  position: absolute;
  top: -10px;
  right: -10px;
  z-index: 10;
  box-shadow: 0 2px 8px rgba(239, 68, 68, 0.3);
}

/* 添加服装卡片 */
.add-garment-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 220px;
  background: linear-gradient(135deg, #fdf4ff, #fae8ff);
  border: 2px dashed #d946ef;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.add-garment-card:hover {
  border-color: #c026d3;
  background: linear-gradient(135deg, #fae8ff, #f3e8ff);
  transform: scale(1.02);
}

.add-icon {
  font-size: 3rem;
  color: #d946ef;
  margin-bottom: 0.5rem;
}

.add-text {
  color: #d946ef;
  font-weight: 600;
  font-size: 1rem;
  margin-bottom: 0.25rem;
}

.add-hint {
  color: #9ca3af;
  font-size: 0.75rem;
}

/* 提示信息 */
.garment-tips {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.75rem 1rem;
  background: linear-gradient(135deg, #eff6ff, #dbeafe);
  border: 1px solid #93c5fd;
  border-radius: 10px;
  color: #1e40af;
  font-size: 0.875rem;
  line-height: 1.5;
}

.garment-tips .el-icon {
  font-size: 1.25rem;
  flex-shrink: 0;
}

/* 移动端优化 */
@media (max-width: 640px) {
  .garments-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 0.75rem;
  }
  
  .garment-upload :deep(.el-upload-dragger) {
    height: 120px;
  }
  
  .garment-preview {
    height: 120px;
  }
  
  .add-garment-card {
    min-height: 180px;
  }
  
  .add-icon {
    font-size: 2.5rem;
  }
  
  .garment-tips {
    font-size: 0.8rem;
    padding: 0.6rem 0.75rem;
  }
}

/* 超小屏幕 */
@media (max-width: 375px) {
  .garments-grid {
    gap: 0.5rem;
  }
  
  .garment-card {
    padding: 0.5rem;
  }
  
  .garment-upload :deep(.el-upload-dragger) {
    height: 100px;
  }
  
  .garment-preview {
    height: 100px;
  }
}
</style>

